﻿using System;
using System.Collections.Generic;
using System.Linq;
using AMM.CustomClassLibrary;
using AMM.DataAccess.Config;
using AMM.Model;
using AMM.Model.Config;

namespace AMM.Business.Config {
    public class BasicsProcessor : BaseProcessor {

        private BasicsRepository _basicsRepository;

        public BasicsProcessor() {
            this._basicsRepository = new BasicsRepository();
        }

        public List<object> FetchBasicsType() {
            return MethodHelper.GetEnumDescriptionToList(typeof(BasicsType));
        }

        public Basic FetchBasicsById(int basicsId) {
            try {
                return this._basicsRepository.FetchBasicsById(basicsId);
            }
            catch (Exception ex) {
                Logger.Error(ex.Message, ex);
                throw this.BuildException("获取指定基本资料数据失败！");
            }
        }

        public List<BasicsViewModel> FetchBasicsByType(BasicsType type) {
            try {
                return this._basicsRepository.FetchBasicsByType((int)type).Select(x => {
                    return new BasicsViewModel() {
                        Key = x.BasicsId,
                        Code = x.Code,
                        Name = x.Name,
                        Description = x.Description,
                        IsEnabled = x.IsEnabled,
                        IsSystem = x.IsSystem,
                        Sequence = x.Sequence
                    };
                }).ToList();
            }
            catch (Exception ex) {
                Logger.Error(ex.Message, ex);
                throw this.BuildException("获取基本资料列表失败！");
            }
        }

        public List<Basic> FetchEnabledBasicsByType(BasicsType type) {
            List<Basic> resultList = this._basicsRepository.FetchBasicsByType((int)type).Where(x => x.IsEnabled).ToList();
            resultList.Insert(0, new Basic());
            return resultList;
        }

        public void Insert(Basic basics) {
            try {
                basics.BasicsId = Guid.NewGuid().GetHashCode();
                this._basicsRepository.Insert(basics);
            }
            catch (Exception ex) {
                Logger.Error(ex.Message, ex);
                throw this.BuildException("插入新基本资料失败！");
            }
        }

        public void Update(Basic basics) {
            try {
                this._basicsRepository.Update(basics);
            }
            catch (Exception ex) {
                Logger.Error(ex.Message, ex);
                throw this.BuildException("更新基本资料失败！");
            }
        }

        public void Delete() {
            try {
                this._basicsRepository.Delete();
            }
            catch (Exception ex) {
                Logger.Error(ex.Message, ex);
                throw this.BuildException("删除基本资料失败！");
            }
        }
    }
}
